package com.doudoukeji.service.Activity.my.edituser.edituserphone;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.doudoukeji.service.Activity.ConstantValue;
import com.doudoukeji.service.Activity.my.edituser.EditUserInfoPresenter;
import com.doudoukeji.service.Activity.my.edituser.EditUserInfoView;
import com.doudoukeji.service.Bean.Token;
import com.doudoukeji.service.Http.MyHttpResponseHandler;
import com.doudoukeji.service.R;
import com.doudoukeji.service.Utils.Util;
import com.loopj.android.http.RequestParams;
import com.sanhai.android.mvp.EduActivity;
import com.sanhai.android.service.http.BusinessClient;
import com.sanhai.android.service.http.Response;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;

//行业界面
public class PhoneNumEditorActivity extends EduActivity implements
        OnFocusChangeListener, EditUserInfoView {
    // topbar部分
    private Button mBtnBack;
    private TextView mTvTitle;

    // 本界面
    private EditText mEtPhone, mEtCode;
    private Button mBtnVerification, mBtnConfirm;
    private String phoneNum;
    private EditUserInfoPresenter presenter;
    private MyCount myCount;

    //EditText文本项集合
    private EditText[] mEdittexts;

    private boolean isStart = false;

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_phonenumeditor);

    }

    @Override
    public void init() {
        // topbar部分
        mBtnBack = (Button) findViewById(R.id.btn_back);
        mBtnBack.setOnClickListener(this);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvTitle.setText("更换手机号");

        // 本界面
        mEtPhone = (EditText) findViewById(R.id.et_phone);



        mEtPhone.setOnFocusChangeListener(this);

        mEtCode = (EditText) findViewById(R.id.et_code);
        // TODO 添加监听 1 行
        mEtCode.setOnFocusChangeListener(this);

        mBtnVerification = (Button) findViewById(R.id.btn_verification);
        mBtnVerification.setOnClickListener(this);
        mBtnVerification.setEnabled(false);

        mBtnConfirm = (Button) findViewById(R.id.btn_confirm);
        mBtnConfirm.setOnClickListener(this);
        mBtnConfirm.setEnabled(false);
        presenter = new EditUserInfoPresenter(this, this);

        //文本集合
        mEdittexts = new EditText[]{mEtPhone, mEtCode};

        //设置文本变化监听器(手机号，验证码，邀请码)
        for (int x = 0; x < mEdittexts.length; x++) {
            setEtInvitTextChangeListener(mEdittexts[x]);
        }

    }


    /**
     * 设置邀请码文本变化监听器
     */
    private void setEtInvitTextChangeListener(EditText mEt) {

        mEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mEtCode.getText().length() == 4 && mEtPhone.getText().length() == 11) {
                    mBtnConfirm.setClickable(true);
                    mBtnConfirm.setEnabled(true);
                    mBtnConfirm
                            .setBackgroundResource(R.drawable.btn_home_selector);
                } else {
                    mBtnConfirm.setClickable(false);
                    mBtnConfirm.setEnabled(false);
                    mBtnConfirm
                            .setBackgroundResource(R.drawable.btn_code_normal);
                }

                if (mEtPhone.getText().length() == 11) {
                    mBtnVerification.setClickable(true);
                    mBtnVerification.setEnabled(true);
                    mBtnVerification
                            .setBackgroundResource(R.drawable.btn_home_selector);
                } else {
                    mBtnVerification.setClickable(false);
                    mBtnVerification.setEnabled(false);
                    mBtnVerification
                            .setBackgroundResource(R.drawable.btn_code_normal);
                }

                //讀秒開始後可不能點擊了哦
                if (isStart){
                    mBtnVerification.setEnabled(false);
                }
            }
        });
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                PhoneNumEditorActivity.this.finish();
                break;
            case R.id.btn_verification:
                if (checkValue()) {
                    getInvitationCode(phoneNum);
                }

                break;
            case R.id.btn_confirm:
                if (checkValue()) {
                    presenter.updateUserInfo(phoneNum, mEtCode.getText().toString(), "", "", "");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.et_phone:
                mEtPhone.setBackgroundResource(R.drawable.et_login_orange);
                mEtCode.setBackgroundResource(R.drawable.et_login_wihte);
                break;
            case R.id.et_code:
                mEtPhone.setBackgroundResource(R.drawable.et_login_wihte);
                mEtCode.setBackgroundResource(R.drawable.et_login_orange);
                break;
            default:
                break;
        }

    }


    public boolean checkValue() {
        phoneNum = mEtPhone.getText().toString().trim();
        if (StringUtils.isBlank(phoneNum)) {
            Toast.makeText(PhoneNumEditorActivity.this, "手机号不能为空",
                    Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!Util.isMobileNo(phoneNum)) {
            Toast.makeText(PhoneNumEditorActivity.this, "请输入正确格式的手机号",
                    Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    /**
     * @param phone 获取验证码
     */
    public void getInvitationCode(String phone) {
        RequestParams params = new RequestParams();
        params.put("phone", phone);
        BusinessClient.post(ConstantValue.intCode, params, new MyHttpResponseHandler() {
            @Override
            public void onMyResponse(Response response) {
                if (response.isSucceed()) {
                    mBtnVerification.setEnabled(false);
                    myCount = new MyCount(60000, 1000);
                    myCount.start();// 请求服务器发送验证码
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                super.onFailure(i, headers, bytes, throwable);
                showToastMessage("请求失败");
            }
        });
    }


    public class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            isStart = true;
        }

        @Override
        public void onFinish() {
            mBtnVerification.setText("获取验证码");
            // sendCode.setBackgroundResource(R.drawable.date_btn_no);
            // sendCode.setTextColor(Color.parseColor("#00923f"));
            mBtnVerification.setEnabled(true);
            isStart=false;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtnVerification.setText(millisUntilFinished / 1000 + "秒");
            mBtnVerification.setTextColor(Color.parseColor("#ffffff"));
        }
    }

    @Override
    public void updateSucced() {
        showToastMessage("修改成功");
        Token.setPhone(phoneNum);
        finish();
    }

    @Override
    public void updateFail() {
        showToastMessage("请求错误");
    }
}
